package top.zackyoung.thirdlogin.login.impl;

import cn.hutool.core.util.RandomUtil;
import org.springframework.stereotype.Service;
import top.zackyoung.thirdlogin.enums.LoginType;
import top.zackyoung.thirdlogin.login.OauthService;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ZackYoung
 * @version 1.0
 * @description
 * @date 2021/6/5 22:16
 */
@Service
public class OauthServiceImpl implements OauthService {
    static Map<String, Set<String>> stateMap = new ConcurrentHashMap<>();

    @Override
    public String genState(LoginType loginType) {
        String state = RandomUtil.randomStringUpper(5);
        stateMap.get(loginType.getName()).add(state);
        return state;
    }

    @Override
    public boolean checkState(LoginType loginType, String state) {
        Set<String> set = stateMap.get(loginType.getName());
        return !set.isEmpty() && set.contains(state);
    }

    static {
        Arrays.stream(LoginType.values()).forEach(OauthServiceImpl::initState);
    }

    private static void initState(LoginType loginType) {
        if (stateMap.get(loginType.getName())==null) {
            stateMap.put(loginType.getName(), new HashSet<>());
        }
    }
}
